import { useRef, useState } from "react"

function UseRefHook() {
    console.log('render');
    // 组件重新渲染时useRef不会被重新初始化
    let num = useRef(0)
    // 数据存储
    const handdleCount = () => {
        setCount(count + 1)
        num.current = count
    }
    // 获取demo
    const divRef = useRef<HTMLDivElement>(null)
    const [count, setCount] = useState(0)
    const handleClick = () => {
        divRef.current!.style.background = 'red'
    }

    // 应用场景示例
    let timmer = useRef<null | NodeJS.Timeout>(null)
    const [val, setVal] = useState(0)
    const start = () => {
        timmer.current = setInterval(() => {

            setVal(prev => prev + 1)
        }, 100)
    }
    const end = () => {
        if (timmer.current) {
            clearInterval(timmer.current)
        }
    }
    return <div>
        <div>ref获取dom元素</div>
        <div ref={divRef}>dom元素</div>
        <button onClick={handleClick}>获取dom元素</button>
        <div>ref用于数据存储</div>
        <div>{count}:{num.current}</div>
        <button onClick={handdleCount}>+</button>
        <div>应用场景示例</div>
        <h1>计时器场景</h1>
        <div>num:{val}</div>
        <button onClick={start}>开始</button>
        <button onClick={end}>结束</button>
    </div>
}

export default UseRefHook